<template>
  <div class="auth-form">
    <div class="auth-form__title">欢迎使用{{ PROJECT_TITLE }}。</div>
    <t-form ref="formInstance" :data="pageData.formData" :rules="pageData.formRules" :colon="false" :label-width="0">
      <t-form-item name="userName">
        <t-input v-model="pageData.formData.userName" clearable placeholder="请输入用户名" />
      </t-form-item>

      <t-form-item name="password">
        <t-input v-model="pageData.formData.password" type="password" clearable placeholder="请输入密码" />
      </t-form-item>

      <t-form-item name="verifyCode">
        <t-input v-model="pageData.formData.verifyCode" clearable placeholder="输入验证码，点击图片更换。" />
        <t-image
          :src="pageData.captchaBase64"
          @click="getCaptchaImageData"
          style="height: 30px; width: 80px; margin-left: 6px"
        />
      </t-form-item>

      <t-form-item>
        <t-checkbox v-model="pageData.rememberMe">记住我</t-checkbox>
      </t-form-item>

      <t-form-item>
        <t-button theme="primary" type="submit" @click="handleSubmit" block>登录</t-button>
      </t-form-item>
    </t-form>
  </div>
</template>

<script lang="ts" setup>
// 框架和组件库
import { reactive, ref, toRaw } from "vue";
import { useRouter } from "vue-router";
import { NotifyPlugin, type FormInstanceFunctions } from "tdesign-vue-next";

// 工具函数
import { http } from "@/utils/fetch";
import { sha256 } from "@/utils/tools";

// API
import { getCaptchaImage } from "@/api/auth";

// 业务数据
import { useUserStore } from "@/stores/modules/user";
import { useMenuStore } from "@/stores/modules/menu";

const router = useRouter();

const userStore = useUserStore();
const menuStore = useMenuStore();

const formInstance = ref<FormInstanceFunctions | null>(null);

const PROJECT_TITLE = import.meta.env.VITE_PROJECT_TITLE;

const pageData = reactive({
  rememberMe: false,
  formData: {
    userName: "",
    password: "",
    verifyCode: "",
    verifyCodeUUID: ""
  },
  formRules: {
    userId: [{ required: true, message: "请输入 ID。", type: "error", trigger: "blur" }],
    password: [
      {
        required: true,
        message: "请输入密码。",
        type: "error",
        trigger: "blur"
      }
    ]
    // verifyCode: [
    //   {
    //     required: true,
    //     message: "请输入验证码。",
    //     type: "error",
    //     trigger: "blur"
    //   }
    // ]
  },
  captchaBase64: "",
  verifyCodeUUID: ""
});

const getCaptchaImageData = async () => {
  const resultData = await getCaptchaImage();
  pageData.captchaBase64 = `data:image/png;base64,${resultData.data.captchaBase64}`;
  pageData.verifyCodeUUID = resultData.data.uuid;
};

const handleSubmit = async () => {
  const validateResult = await formInstance?.value?.validate();
  if (validateResult === true) {
    const postFormData = structuredClone(toRaw(pageData.formData));
    postFormData.password = await sha256(postFormData.password);

    // 清除旧的 token，防止错乱。
    window.sessionStorage.removeItem("userAuthToken");
    window.localStorage.removeItem("userAuthToken");

    postFormData.verifyCodeUUID = pageData.verifyCodeUUID;

    const resultData = await http("POST", "/auth/login", postFormData);

    // console.log(resultData);
    if (resultData.code === 200) {
      // 将登陆信息存储到 Pinia Store 里面
      userStore.setUserData(resultData.data.user);

      if (pageData.rememberMe) {
        window.localStorage.setItem("userAuthToken", resultData.data.token);
      } else {
        window.sessionStorage.setItem("userAuthToken", resultData.data.token);
      }

      menuStore.setMenuData(resultData.data.menus);
      menuStore.setActiveMenu("dashboard_home");

      await NotifyPlugin.success({ title: "登录成功", content: `欢迎使用${import.meta.env.VITE_PROJECT_TITLE}！` });
      router.push("/dashboard");
    } else {
      getCaptchaImageData();
    }
  }
};

getCaptchaImageData();
</script>

<style lang="less" scoped>
@import url("../index.less");
</style>
